'use strict';

angular.module('SystemManage').controller('UserController', ['$rootScope', '$scope', '$cookies', '$stateParams', '$modal', 'User', 'PublicModule', 'PublicFunction', 'PublicEnum', 'BarcodeEnum', 'PublicService', '$location', 'Authentication', 'ImageCompress',
    function ($rootScope, $scope, $cookies, $stateParams, $modal, User, PublicModule, PublicFunction, PublicEnum, BarcodeEnum, PublicService, $location, Authentication, ImageCompress) {
        //$scope.authentication = Authentication;
        $scope.data = {
            myCroppedImage: 'users/img/default.png',
            url: 'api/fileUpload',
            Authorization: 'Bearer ' + $cookies.get('U9USS'),
            uploadType: 'avatar',
            filePath: './public/users/img/'
        };
        $scope.myImage = '';
        var myModal = $modal({
            scope: $scope,
            placement: 'center',
            show: false,
            animation: 'am-fade-and-scale',
            templateUrl: 'modules/User/client/views/avatar.client.view.html',
            backdrop: false
        });
        $scope.btnSave = function () {
            if ($scope.Module.User.FocusedRecord.Code === undefined ||
                $scope.Module.User.FocusedRecord.Code.trim() === "") {
                PublicFunction.alert("用户名为空！", "保存错误");
                return;
            }
            if ($scope.Module.User.FocusedRecord.Name === undefined ||
                $scope.Module.User.FocusedRecord.Name.trim() === "") {
                PublicFunction.alert("名称不能为空！", "保存错误");
                return;
            }

            var roleIds = [];
            for (var i = 0; i < $scope.Module._Role.Records.length; i++) {
                if ($scope.Module._Role.Records[i].RoleId === undefined ||
                    $scope.Module._Role.Records[i].RoleId === null ||
                    $scope.Module._Role.Records[i].RoleId === "") {
                    PublicFunction.alert("角色不能为空！", "保存错误");
                    return;
                }
                for (var j = 0; j < roleIds.length; j++) {
                    if (roleIds[j] === $scope.Module._Role.Records[i].RoleId) {
                        PublicFunction.alert("角色不能重复！", "保存错误");
                        return;
                    }
                }
                roleIds.push($scope.Module._Role.Records[i].RoleId);
            }

            $scope.Module.User.FocusedRecord.Roles = roleIds;
            if ($scope.Module.User.FocusedRecord.RowStatus === PublicEnum.RowStatus.UnChange) {
                $scope.Module.User.FocusedRecord.RowStatus = PublicEnum.RowStatus.Modify;
            }

            if ($scope.data.myCroppedImage.indexOf('base64') < 0) {
                $scope.Module.User.FocusedRecord.Image = ($scope.Module.User.FocusedRecord.Image ? $scope.Module.User.FocusedRecord.Image : $scope.data.myCroppedImage);
                saveAll();
            } else {
                //author:jiadx先上传头像，在保存其他内容
                var form = new FormData();
                form.append('file', convertBase64UrlToBlob($scope.data.myCroppedImage));
                form.append('uploadType', $scope.data.uploadType);
                form.append('filePath', $scope.data.filePath);
                var request = new XMLHttpRequest();
                request.open("POST", $scope.data.url);
                request.setRequestHeader("Authorization", $scope.data.Authorization);
                request.send(form);
                //上传之后返回路径，进行入库保存
                request.onreadystatechange = function () {
                    if (request.status == '200' && request.readyState == 4) {
                        $scope.Module.User.FocusedRecord.Image = eval("(" + request.responseText + ")").path;
                        saveAll();
                    } else if (request.status == '400' || request.status == '404') {
                        PublicFunction.tip('保存失败', '图片上传失败');
                    }
                };
            }

            function saveAll() {
                //执行save方法
                if ($scope.Module.User.FocusedRecord.RowStatus == PublicEnum.RowStatus.Insert) {
                    if ($scope.Module.User.FocusedRecord.UniqueID != undefined &&
                        $scope.Module.User.FocusedRecord.UniqueID != null) {

                        var insertUserRecord = $scope.Module.User.FocusedRecord;
                        $scope.Module.User.save(function () {
                            $scope.Module.BarcodeMaster.add();
                            $scope.Module.BarcodeMaster.FocusedRecord.Barcode = $scope.Module.User.FocusedRecord.UniqueID;
                            $scope.Module.BarcodeMaster.FocusedRecord.BarcodeType = BarcodeEnum.BarcodeType.Person.Value;
                            $scope.Module.BarcodeMaster.FocusedRecord.EntityID = $scope.Module.User.FocusedRecord._id;
                            $scope.Module.BarcodeMaster.save(function () {
                                    updateWebAfterSave();
                                    PublicFunction.tip('保存成功', '用户编码：' + $scope.Module.User.FocusedRecord.Code);
                                },
                                function (err) {
                                    $scope.Module.User.FocusedRecord.RowStatus = PublicEnum.RowStatus.Delete;
                                    $scope.Module.User.save(function () {
                                        updateWebAfterSave();
                                    });
                                    $scope.Module.User.FocusedRecord = insertUserRecord;
                                    PublicFunction.alert(err.data.message, err.data.title);
                                });
                        });
                    } else {
                        $scope.Module.User.save(function () {
                            updateWebAfterSave();
                        });
                        // uploadImage();
                    }
                } else if ($scope.Module.User.FocusedRecord.RowStatus == PublicEnum.RowStatus.Modify) {
                    if ($scope.Module.User.FocusedRecord.UniqueID != oldUniqueID) {
                        if (oldUniqueID != null && oldUniqueID != undefined && oldUniqueID != '') {
                            $scope.Module.BarcodeMaster.find({Barcode: oldUniqueID}, null, function (records) {
                                $scope.Module.BarcodeMaster.clearRecords();
                                $scope.Module.BarcodeMaster.Records = records;
                                $scope.Module.BarcodeMaster.Records[0].Barcode = $scope.Module.User.FocusedRecord.UniqueID;
                                $scope.Module.BarcodeMaster.Records[0].BarcodeType = BarcodeEnum.BarcodeType.Person.Value;
                                $scope.Module.BarcodeMaster.Records[0].RowStatus = PublicEnum.RowStatus.Modify;

                                saves();
                            });
                        } else {
                            $scope.Module.BarcodeMaster.add();
                            $scope.Module.BarcodeMaster.FocusedRecord.Barcode = $scope.Module.User.FocusedRecord.UniqueID;
                            $scope.Module.BarcodeMaster.Records[0].BarcodeType = BarcodeEnum.BarcodeType.Person.Value;
                            $scope.Module.BarcodeMaster.FocusedRecord.BarcodeType = BarcodeEnum.BarcodeType.Person.Value;

                            saves();
                        }
                    } else {
                        $scope.Module.User.save(function () {
                            updateWebAfterSave();
                        });
                        // uploadImage();
                    }
                }
            }
        };
        var saves = function () {
            var saveDatas = [];
            saveDatas.push({
                EntityName: 'User',
                Records: [$scope.Module.User.FocusedRecord]
            });
            saveDatas.push({
                EntityName: 'BarcodeMaster',
                Records: [$scope.Module.BarcodeMaster.FocusedRecord]
            });

            PublicService.saves(saveDatas, function (res) {
                //刷新数据
                $scope.Module.User.find({Code: $scope.Module.User.FocusedRecord.Code}, function (records) {
                    $scope.Module.User.FocusedRecord = records[0];
                });
                User.queryMe().then(function () {
                    $rootScope.$broadcast('profileChange');
                });
                PublicFunction.tip('保存成功', '用户编码：' + $scope.Module.User.FocusedRecord.Code);
            });
        };

        var oldUniqueID = '';
        $scope.btnCancel = function () {
            $scope.Module.User.cancel(loadRoles);
        };
        $scope.btnAdd = function () {
            $scope.Module.User.add();
            $scope.data.myCroppedImage = 'users/img/default.png';
            $scope.myImage = '';
            loadRoles();
        };
        $scope.btnDelete = function () {
            if ($scope.Module.User.UniqueID != null && $scope.Module.User.UniqueID != null && $scope.Module.User.UniqueID != '') {
                //删除条码主档
                PublicService.delete('BarcodeMaster', {Barcode: $scope.Module.User.UniqueID});
            }
            $scope.Module.User.delete(loadRoles);
        };
        $scope.btnList = function () {
            $location.url('/index/User/List');
        };
        $scope.btnFirstPage = function () {
            $scope.Module.User.firstPage(loadRoles);
        };
        $scope.btnPrePage = function () {
            $scope.Module.User.prePage(loadRoles);
        };
        $scope.btnNextPage = function () {
            $scope.Module.User.nextPage(loadRoles);
        };
        $scope.btnLastPage = function () {
            $scope.Module.User.lastPage(loadRoles);
        };
        $scope.btnFindChange = function () {
            loadRoles();
        };
        $scope.refBeforeShow = function (refScope) {
            var roleIds = [];
            for (var i = 0; i < $scope.Module._Role.Records.length; i++) {
                if ($scope.Module._Role.Records[i].RoleId !== undefined && $scope.Module._Role.Records[i].RoleId !== "") {
                    roleIds.push($scope.Module._Role.Records[i].RoleId);
                }
            }
            refScope.Module.QueryParameter.Condition = {
                _id: {
                    $nin: roleIds
                }
            };
        };
        $scope.$on('serial', function (event, data) {
            if ($scope.Module.User.FocusedRecord.UniqueID != null && $scope.Module.User.FocusedRecord.UniqueID != undefined &&
                $scope.Module.User.FocusedRecord.UniqueID != hexToNumber(data).toString()) {
                PublicFunction.confirm("确定要修改芯片吗？", "修改确认").then(function (result) {
                    if (result) {
                        $scope.Module.User.FocusedRecord.UniqueID = hexToNumber(data).toString();
                    }
                });
            } else {
                $scope.Module.User.FocusedRecord.UniqueID = hexToNumber(data).toString();
            }
            $scope.$digest();
        });

        $scope.openAvatar = function () {
            myModal.$promise.then(myModal.show);
        };
        $scope.$on('modal.show', function () {
            if ($scope.myImage == '') {
                if ($scope.Module.User.FocusedRecord.Image) {
                    $scope.data.myCroppedImage = $scope.Module.User.FocusedRecord.Image;
                } else {
                    $scope.data.myCroppedImage = 'users/img/default.png';
                }
            }
            var handleFileSelect = function (evt) {
                var file = evt.currentTarget.files[0];
                var reader = new FileReader();
                reader.onload = function (evt) {
                    $scope.$apply(function ($scope) {
                        var uri = evt.target.result;
                        var imgType = 'image/png';
                        if ('jpeg' == uri.substring(11, 15)) {
                            imgType = 'image/jpeg';
                        }
                        ImageCompress._createImage(uri, {
                            type: imgType
                        }).then(function (data) {
                            $scope.myImage = data;
                        });
                    });
                };
                reader.readAsDataURL(file);
            };
            angular.element(document.querySelector('#file')).on('change', handleFileSelect);
        });

        //将base64转成Blob
        function convertBase64UrlToBlob(urlData) {
            var bytes = window.atob(urlData.split(',')[1]);
            //去掉url的头，并转换为byte
            //处理异常,将ascii码小于0的转换为大于0
            var ab = new ArrayBuffer(bytes.length);
            var ia = new Uint8Array(ab);
            for (var i = 0; i < bytes.length; i++) {
                ia[i] = bytes.charCodeAt(i);
            }

            return new Blob([ab], {type: 'image/png'});
        }

        function uploadImage() {
            var form = new FormData();
            form.append('file', convertBase64UrlToBlob($scope.data.myCroppedImage));
            form.append('uploadType', $scope.data.uploadType);
            form.append('filePath', $scope.data.filePath);
            var request = new XMLHttpRequest();
            request.open("POST", $scope.data.url);
            request.setRequestHeader("Authorization", $scope.data.Authorization);
            request.send(form);
            request.onreadystatechange = function () {
                if (request.status == '200' && request.readyState == 4) {
                    $scope.Module.User.FocusedRecord.Image = eval("(" + request.responseText + ")").path;
                    //执行save方法
                    $scope.Module.User.save(function () {
                        updateWebAfterSave();
                    });
                } else if (request.status == '400' || request.status == '404') {
                    PublicFunction.tip('保存失败', '图片上传失败');
                }

            };

        }

        function updateWebAfterSave() {
            User.queryMe().then(function () {
                $rootScope.$broadcast('profileChange');
            });
        }

        $scope.uploadAvatar = function () {
            //临时显示图片
            $scope.Module.User.FocusedRecord.Image = $scope.data.myCroppedImage;

            myModal.$promise.then(myModal.hide);
        };

        $scope.selectPhoto = function () {
            var ie = navigator.appName == "Microsoft Internet Explorer" ? true : false;
            if (ie) {
                document.getElementById("file").click();
            } else {
                var a = document.createEvent("MouseEvents");
                a.initEvent("click", true, true);
                document.getElementById("file").dispatchEvent(a);
            }
        };

        var loadRoles = function () {
            //$scope.Module.Menu.QueryParameter.Condition = ;
            oldUniqueID = $scope.Module.User.FocusedRecord.UniqueID;
            if ($scope.Module.User.FocusedRecord.Roles !== undefined && $scope.Module.User.FocusedRecord.Roles !== null) {
                $scope.Module.Role.find({
                    _id: {
                        $in: $scope.Module.User.FocusedRecord.Roles
                    }
                }, null, function (_roleReords) {
                    setRoles(_roleReords);
                });
            } else {
                setRoles([]);
            }
        };
        var setRoles = function (roleReords) {
            $scope.Module._Role.Records = [];
            for (var i = 0; i < roleReords.length; i++) {
                var newRecord = $scope.Module._Role.add();
                newRecord.RoleId = roleReords[i]._id;
                newRecord.RoleCode = roleReords[i].Code;
                newRecord.RoleName = roleReords[i].Name;
            }
            $scope.Module._Role.firstPage();
        };

        //初始化
        PublicModule.initModule($scope, 'User');
        //$scope.Module.User.QueryParameter.Condition = {Code: {$ne: 'admin'}};
        $scope.Module.User.QueryParameter.Populate = {
            path: 'Department',
            select: 'Code Name'
        };
        PublicModule.initModule($scope, 'BarcodeMaster');

        PublicModule.initModule($scope, 'Role');
        $scope.Module.Role.LoadMode = PublicEnum.LoadMode.CacheAndNoPaging;

        PublicModule.initModule($scope, '_Role');
        $scope.Module._Role.PageSize = 10;
        $scope.Module._Role.LoadMode = PublicEnum.LoadMode.CacheAndNoPaging;

        if ($stateParams.id) {
            $scope.Module.User.findById($stateParams.id, function (record) {
                $scope.Module.User.FocusedRecord = record;
                loadRoles();
            });
        } else {
            $scope.btnAdd();
        }
    }
]);
